package com.example.demo.web

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.sytech.power_bank.helper.hexToByte
import com.sytech.power_bank.helper.toHexString
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.File
import java.nio.charset.Charset
import java.security.SecureRandom
import java.util.*
import javax.annotation.PostConstruct
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.DESKeySpec
import javax.servlet.http.HttpServletRequest

/**
 * 租赁柜状态上传
 *租赁柜取操作指令
 * Created by li on 2017/7/4.
 */
@RestController
@RequestMapping("/device")
class PowerBankDeviceInterface(
) {
    companion object {
        var orderStr=""
        var  upfilecontent: String=""
        var  upfilename: String=""
    }
    var password: String = "Sy320490"
    val keyFactory = SecretKeyFactory.getInstance("DES")
    val cipher = Cipher.getInstance("DES/ECB/NoPadding")
    @PostConstruct
    fun initN() {
        cipher.init(Cipher.DECRYPT_MODE, keyFactory.
                generateSecret(
                        DESKeySpec(password.toByteArray())),
                SecureRandom())
    }
    /**
     * 租赁柜状态上传
     */
    @RequestMapping(value = "/upstate", produces = arrayOf("text/plain"))
    fun upState(@RequestBody bankBoxUp: PowerBankBoxStatus): String {
        println("${Date()}-状态更新：\n$bankBoxUp")
        return "{}"
    }

    /**
     * 充电柜取指令,注意大小端
     */
    var ff=0
    @RequestMapping("/getOrder")
    fun getOrder(@RequestBody boxGetOrderRequest: PowerBankBoxGetOrderRequest,req:HttpServletRequest): String {
        ff++
        println("${Date()}-($ff)获取指令请求：\n$boxGetOrderRequest")
        if(orderStr==""){
            println("${Date()}-($ff)获取指令返回空数据。")
            return ""
        }
        var desKeyBytes=ByteArray(0)
        try {
             desKeyBytes = cipher.doFinal(boxGetOrderRequest.key.hexToByte())
        }catch (e:Exception){
            println("${Date()}-($ff)解密密钥失败。")
            return ""
        }
        val cipher = Cipher.getInstance("DES/ECB/NoPadding")
        cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generateSecret(DESKeySpec(desKeyBytes)), SecureRandom())
        // return PowerBankBoxGetOrderResponse(opid = order.opid, result = cipher.doFinal(order.opCode.toByteArray()).toHexString())
        var rt= PowerBankBoxGetOrderResponse(opid = 1, result = cipher.doFinal(orderStr.hexToByte()).toHexString())
        var rts= jacksonObjectMapper().writeValueAsString(rt ?: return "{}")
        println("${Date()}-($ff)取指令返回数据:\n$rts")
        return rts
    }

    /**
     *返回指令执行结果
     */
    @RequestMapping("/returnStatus")
    fun returnStatus(@RequestBody orderResult: PowerBankBoxUpOrderResult): String {
        orderStr=""
        println("${Date()}-设备上传执行状态:$orderResult")
        return "{}"
    }

    /**
    下载升级包
     */
    var ii=0
    @RequestMapping("/getPack")
    fun getPack(id: String?, idx: Long?, fname: String?): String {
        ii++
        println("${Date()}-($ii)下载升级包参数：(id=$id,idx=$idx,fname=$fname)")
        var filebys = upfilecontent
        var fname = upfilename
        var fsize = 0L
        var fvers = "ChargeBOX_Update_4G.hex"
        var hvers = "ChargeBOX_Update_4G.hex"
        var ok = false
        val maxLength = 1024
        val perLength = 800
        val st = idx?.toInt() ?: 0
        var et=st + perLength;
        if(et>filebys.length)et=filebys.length
        var s = filebys.substring(st, et)
        s = s.substring(0, s.lastIndexOf("\r\n")) + "\r\n"
        println("${Date()}-($ii)下载升级包返回数据：\n$s")
        return s
    }

    /*
     * 查询最新版本
     */
    var kk=0
    @RequestMapping(value = "/checkUpdate")
    fun checkUpdate(@RequestBody version: DeviceVersion): String {
        //return """{ fname = "", fsize = 0, fvers = "", hvers = ""}"""
        kk++
        println("${Date()}-($kk)查询最新版本，参数：$version")
        if(upfilecontent==""){
            return ""
        }
        var filebys = upfilecontent
        var fname = upfilename
        var fsize = 0L
        var fvers = "ChargeBOX_Update_4G.hex"
        var hvers = "ChargeBOX_Update_4G.hex"
        fsize =filebys.length.toLong()
        val fst = filebys.indexOf(":10040000") + ":10040000".length
        val hst = filebys.indexOf(":10050000") + ":10040000".length
        val hv = StringBuilder(50)
        val fv = StringBuilder(50)
        (hst..fsize.toInt() step 2)
                .takeWhile { !(filebys[it] == '0' && filebys[it + 1] == '0') }
                .forEach { hv.append(filebys[it]).append(filebys[it + 1]) }
        (fst..fsize.toInt() step 2)
                .takeWhile { !(filebys[it] == '0' && filebys[it + 1] == '0') }
                .forEach { fv.append(filebys[it]).append(filebys[it + 1]) }

        hvers = String(hv.toString().hexToByte())
        fvers = String(fv.toString().hexToByte())
        var rt= jacksonObjectMapper().writeValueAsString(ResponseDeviceVersion(
                fname = fname, fsize = fsize.toString(), fvers = fvers, hvers = hvers
        ))
        println("${Date()}-($kk)查询最新版本返回数据:\n$rt")
        return rt
    }
}
